<?php
namespace App\Job;

use Hyperf\AsyncQueue\Job;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use App\Service\FootballArticleService;
use App\Helper\SeoHelper;

class FootballArticleJob extends Job
{
    protected $productId;
    protected $getData;
    protected $logger;

    /**
     * @var FootballArticleService
     */
    protected $footballArticleService;

    public function __construct(int $productId, array $getData, LoggerFactory $loggerFactory)
    {
        $this->productId = $productId;
        $this->getData = $getData;
        $this->logger = $loggerFactory->get('article', 'article');
    }

    public function handle()
    {
        try {
            $webname = $this->getData['webname'] ?? '';
            $articleKeywords = trim($this->getData['keywords'] ?? '');

            if (empty($webname)) {
                $this->logger->warning("webname为空，跳过任务", [
                    'product_id' => $this->productId
                ]);
                return;
            }

            $conn = Db::connection($webname);
            $product = $conn->selectOne("
                SELECT 
                    p.product_id, 
                    pd.name AS product_name, 
                    p.image, 
                    pd.tag, 
                    pd.description, 
                    pd.meta_title, 
                    pd.meta_description 
                FROM oc_product p 
                JOIN oc_product_description pd 
                    ON p.product_id = pd.product_id 
                WHERE p.product_id = :pid LIMIT 1",
                ['pid' => $this->productId]
            );

            if (!$product) {
                $this->logger->warning("未找到产品", [
                    'product_id' => $this->productId,
                    'webname' => $webname
                ]);
                return;
            }

            $this->logger->info("找到产品", [
                'product_id' => $product->product_id,
                'product_name' => $product->product_name,
                'webname' => $webname
            ]);

            $productImageUrl = "https://www.".filter_var($webname, FILTER_SANITIZE_URL)."/image/".filter_var($product->image, FILTER_SANITIZE_URL);

            $articleService = ApplicationContext::getContainer()->get(FootballArticleService::class);

            $article = $articleService->generateArticle([
                'name' => $product->product_name,
                'description' => strip_tags(html_entity_decode($product->description)),
                'meta_title' => $product->meta_title,
                'meta_description' => $product->meta_description,
                'tags' => $product->tag,
                'keywords' => $articleKeywords,
                'webname' => $webname,
                'images' => $productImageUrl,
                'url' => "https://www.".filter_var($webname, FILTER_SANITIZE_URL)."/index.php?route=product/product&product_id=".filter_var($product->product_id, FILTER_SANITIZE_NUMBER_INT)
            ]);

            if (!is_array($article) || empty($article['post_title'])) {
                $this->logger->warning("AI返回文章为空", [
                    'product_id' => $this->productId,
                    'webname' => $webname
                ]);
                return;
            }

            $conn->beginTransaction();

            try {
                $conn->insert("INSERT INTO oc_blog (allow_comment, count_read, sort_order, status, author, date_added, image) VALUES (1, 1, 1, 0, 'John', NOW(), :img)", [
                    'img' => $product->image
                ]);
                $postId = $conn->getPdo()->lastInsertId();

                $conn->insert("INSERT INTO oc_blog_description (blog_id, language_id, title, page_title, meta_keyword, meta_description, short_description, description, tags) VALUES (:bid, 1, :title, :page_title, :keyword, :desc, :short, :full, :tags)", [
                    'bid' => $postId,
                    'title' => $article['post_title'],
                    'page_title' => $article['meta_tag_title'],
                    'keyword' => $article['meta_keywords'] ?? '',
                    'desc' => $article['meta_tag_description'],
                    'short' => $article['short_description'],
                    'full' => $article['description'],
                    'tags' => $article['tags'] ?? ''
                ]);

                $conn->insert("INSERT INTO oc_blog_to_store (blog_id, store_id) VALUES (:bid, 0)", ['bid' => $postId]);
                $conn->insert("INSERT INTO oc_blog_to_layout (blog_id, store_id, layout_id) VALUES (:bid, 0, 0)", ['bid' => $postId]);
                $conn->insert("INSERT INTO oc_blog_to_category (blog_id, blog_category_id) VALUES (:bid, 49)", ['bid' => $postId]);
                $conn->insert("INSERT INTO oc_blog_related_products (blog_id, related_id) VALUES (:bid, :rid)", [
                    'bid' => $postId,
                    'rid' => $product->product_id
                ]);

                $seoUrl = SeoHelper::generateSeoUrl($article['post_title']);
                $conn->insert("INSERT INTO oc_url_alias (query, keyword, lang, store_id, language_id) VALUES (:aquery, :akeyword, :alang, :astore_id, :alanguage_id)", [
                    'aquery' => "blog_id=".$postId,
                    'akeyword' => $seoUrl,
                    'alang' => 1,
                    'astore_id' => 0,
                    'alanguage_id' => 0
                ]);

                $conn->commit();
                $this->logger->info("文章生成成功", [
                    'product_id' => $this->productId,
                    'blog_id' => $postId,
                    'webname' => $webname
                ]);

            } catch (\Throwable $e) {
                $conn->rollBack();
                throw $e;
            }

        } catch (\Throwable $e) {
            $this->logger->error("任务处理失败", [
                'product_id' => $this->productId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            throw $e;
        }
    }
}
